/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kz.dasm.baing;

import java.io.Serializable;
import java.sql.SQLException;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.sql.DataSource;
import kz.dasm.baing.db.DbApi;

/**
 *
 * @author Kreedmart
 */
//@ManagedBean
@SessionScoped
public class Authenticator implements Serializable {

  private static final long serialVersionUID = 876349387L;
  
  @Inject
  private DataSource ds;
  
  private DbApi dbApi;
  private String userName;
  private Integer userId;


  @PostConstruct
  void init() {
    dbApi = new DbApi(ds);
  }


  public String getUserName() {
    return userName;
  }


  public Integer getUserId() {
    return userId;
  }


  public boolean authenticate(String userName, String password)
          throws SQLException {

    Integer uid = dbApi.initUser(userName, password);

    if (uid != null) {
      this.userName = userName;
      this.userId = uid;
      return true;
    }

//    resetAutorization();    
    return false;
  }


  public boolean isAuthorized() {
    return getUserId() != null && getUserName() != null;
  }


  public void resetAutorization() {
    userId = null;
    userName = null;
  }
}
